<template>
    <div class="tsPage page">
        <div class="header">
            <div class="toolbar">
                <div class="logo">
                    <div class="img">
                        <img :src="logoImg" alt="">
                    </div>
                    <div class="title">
                        <div class="master">{{athsInfo.eventName}}</div>
                        <div class="detail">{{athsInfo.phaseName}}</div>
                    </div>
                </div>

                <div class="lights">
                    <div :class="(tsInfo.lightW>0)?'W lig active':'W lig '"></div>
                    <div :class="(tsInfo.lightR>0)?'R lig active':'R lig '"></div>
                    <div :class="(tsInfo.lightG>0)?'G lig active':'G lig '"></div>
                    <div :class="(tsInfo.lightw>0)?'w lig active':'w lig '"></div>
                </div>
 
                <div class="acs">
                    <ul class="lstAcs">
                        <li><i class="fa fa-refresh"></i> <div class="txt">刷新</div></li> 
                        <li><i class="fa fa-exchange" @click="acChangePos"></i> <div class="txt">换边</div></li> 
                        <li><i class="fa fa-reply" @click="acBack"></i> <div class="txt">返回</div></li> 
                    </ul>
                </div>
            </div>
        </div>
        <div class="body">
            <div class="pannel">
                <div class="player">
                    <div class="athlete">
                        <el-button type="danger" ><i class="fa fa-flag"></i> 弃权</el-button>
                        <el-button  v-show="athsInfo.matchType =='TM'" type="warning"><i class="fa fa-flag"></i> 替补</el-button>
                        <div class="delegation">{{home.delegation}}</div>
                        <div class="name">{{home.name}}</div>
                    </div>
                    <div class="result">
                        <div class="score">{{tsInfo.homeScore}}</div>
                        <div class="flags">
                            <div :class="tsInfo.homeYello>0?'yello flag active':'yello flag'"></div>
                            <div :class="tsInfo.homeRed>0?'red flag active':'red flag'"></div> 
                        </div>
                        <div v-show="tsInfo.homeWinFlag>0" class="winFlag">
                            <img :src="winFlagImg" alt="">
                        </div>
                    </div>
                </div>
                <div class="sets">
                    
                    <div class="timeClock">{{tsInfo.currentTm}}</div>
                    <ul class="lstSets">
                        <li
                            v-for="(set,setIndex) in setCounts[athsInfo.matchType]"
                            :key="setIndex"
                            :class = "tsInfo.currentSet==set?'active':''"
                        >
                            <div class="setItem">
                               第 {{set}} 局
                            </div>
                        </li>
                    </ul>

                </div>
                <div class="player">
                    <div class="athlete">
                        <div class="delegation">{{away.name}}</div>
                        <div class="name">{{away.delegation}}</div>
                        <el-button v-show="athsInfo.matchType =='TM'" type="warning"><i class="fa fa-flag"></i> 替补</el-button>
                        <el-button type="danger" ><i class="fa fa-flag"></i> 弃权</el-button>
                    </div>
                    <div class="result">
                        <div class="score">{{tsInfo.awayScore}}</div>
                        <div class="flags">
                            <div :class="tsInfo.awayYello>0?'yello flag active':'yello flag'"></div>
                            <div :class="tsInfo.awayRed>0?'red flag active':'red flag'"></div> 
                        </div>
                        <div v-show="tsInfo.awayWinFlag>0" class="winFlag">
                            <img :src="winFlagImg" alt="">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import mqtt from "mqtt"; 
    class TMqClient{
        constructor(){
            this.config={
                url:"ws://dq.hhdata.cn:42026/mqtt",
                uid:"tsweb",
                pwd:"Hhuc1115",
                autoSubTopics:[]
            };
            this.options={
                clientId:"",
                keepalive:60,
                clean:true,
                reconnectPeriod:1000,
                connectTimeout:10000,
                username:"",
                password:"" 
            };
            this.client = null;
            this.clientId = "";
            this.onMessage = (topic , messageStr)=>{};
        };
        open(){
            var me = this;
            return new Promise((success , faild)=>{
                try{
                    me.close();
                    var clientId = ["mid" , ( new Date()).getTime().toString()].join("");
                    var options = JSON.parse(JSON.stringify(me.options));
                    options.clientId = clientId;
                    options.username = me.config.uid;
                    options.password = me.config.pwd;
                    var client = mqtt.connect(me.config.url, options);
                    client.on("connect",(e)=>{
                        console.log('mqclient is connected.');
                        client.subscribe(me.config.autoSubTopics,(error)=>{
                            if( error && error!=null){
                                console.log('subscribe faild.')
                            }
                            else{
                                console.log('subscribe success.');
                            }
                        });
                        me.client = client;
                        me.clientId = clientId;
                        success();
                    });
                    client.on("reconnect",(e)=>{
                        console.log("mqclient is reconnecting ...");
                    });
                    client.on("close",(e)=>{
                        console.log("mqclient is closed .");
                    });
                    client.on("error",(e)=>{
                        console.log("mqclient connect faild.");
                    });
                    client.on("message",(topic, message)=>{
                        console.log("recieve message. ",topic , message.toString());
                        if( me.onMessage && me.onMessage!=null){
                            try {
                                me.onMessage(topic , message.toString());
                            } catch (error) {
                                console.log(error);
                            }
                        }
                    }); 
                }
                catch(er){
                    console.log(er);
                    success();
                }
            });
        };
        close(){
            var me = this;
            try{
                if( me.client && me.client!=null && me.client.connected){
                    me.client.end();
                }
                me.clientId = "";
                me.client = null;
            }
            catch(er){
                console.log(er);
            }
        };
        isConnected(){
            var me = this;
            var res = false;
            try{
                res = me.client && me.client!=null && me.client.connected;
            }
            catch(er){
                console.log(er);
            }
            return res;
        };
    }
    class TTsInfo{
        constructor(){
            this.tsCode ="";
            this.lightR=0;
            this.lightG=0;
            this.lightW=0;
            this.lightw=0;
            this.homeScore=0;
            this.homeYello=1;
            this.homeRed=0;
            this.homeWinFlag=0;
            this.awayScore=0;
            this.awayYello=0;
            this.awayRed=1;
            this.awayWinFlag=1;
            this.currentSet =1;
            this.currentTm="03:00";
        }
    }  
    const mqClient=new TMqClient();
    export default {
        mounted() {
            var me = this;
            try{ 
                me.init();
                me.openMqClient();
            }
            catch(er){
                console.log(er);
            }   
        },
        data() {
            return {
                logoImg:require("../res/imgs/logo.png"),
                winFlagImg:require("../res/imgs/winFlag.jpg"),
                changePosFlag:0,
                athsInfo:{},
                home:{},
                away:{},
                tsInfo:new TTsInfo(),
                sets:[],
                setCounts:{
                    P:[1],
                    IM:[1,2,3],
                    TM:[1],
                    TX:[1],
                },
                mqClient : new TMqClient()
            };
        },
        methods: {
            init() {
                var me = this;
                try{ 
                    me.tsInfo.tsCode="fets01";
                    me.athsInfo = me.$route.query;
                    me.updateAthInfo();
                    console.log(me.athsInfo);
                    
                }
                catch(er){
                    console.log(er);
                }          
            }, 
            openMqClient() {
                var me = this;
                try{ 
                    var flag = mqClient && mqClient!=null ? mqClient.isConnected():false;
                    if( !flag){
                        if( !(mqClient && mqClient!=null)){
                            mqClient = new TMqClient();
                        }
                        mqClient.close();
                        mqClient.onMessage=(topic, message)=>{
                            try {
                                var flag =  this.$route.path.indexOf('/tsInfo')>0;
                                if( flag){
                                    var msg = JSON.parse(message);
                                    console.log('recMessage',msg);
                                    if( msg.action && msg.action=="data" && msg.Code == me.tsInfo.tsCode){
                                        me.updateTsInfoData(msg);
                                    }
                                    else if( msg.action && msg.action=="currentTime" && msg.Code == me.tsInfo.tsCode){
                                        me.updateTsInfoTime(msg);
                                    }
                                }
                            } catch (error) {
                                console.log(error);
                            }
                        };
                        var dataTopic = ["/fe2023/ts","data" , me.tsInfo.tsCode].join("/");
                        var tmTopic = ["/fe2023/ts","time" , me.tsInfo.tsCode].join("/");
                        mqClient.config.autoSubTopics=[dataTopic , tmTopic];
                        mqClient.open();
                    }
                    
                }
                catch(er){
                    console.log(er);
                }          
            }, 
            updateAthInfo() {
                var me = this;
                try{ 
                    me.home = me.changePosFlag>0?{
                       delegation: me.$route.query.AwayDelegation ,
                       name :me.$route.query.AwayName ,
                       position:me.$route.query.AwayPosition
                    }:{
                       delegation: me.$route.query.HomeDelegation ,
                       name :me.$route.query.HomeName ,
                       position:me.$route.query.HomePosition
                    };
                    me.away = me.changePosFlag>0?{
                       delegation: me.$route.query.HomeDelegation ,
                       name :me.$route.query.HomeName ,
                       position:me.$route.query.HomePosition
                    }:{
                       delegation: me.$route.query.AwayDelegation ,
                       name :me.$route.query.AwayName ,
                       position:me.$route.query.AwayPosition
                    };
                }
                catch(er){
                    console.log(er);
                }          
            },
            acChangePos() {
                var me = this;
                try{ 
                    me.changePosFlag = me.changePosFlag >0?0:1;
                    me.updateAthInfo();
                }
                catch(er){
                    console.log(er);
                }          
            },
            acBack() {
                var me = this;
                try{ 
                    me.$router.back();
                }
                catch(er){
                    console.log(er);
                }          
            },
            updateTsInfoData( msg ) {
                var me = this;
                try{  
                    me.tsInfo.lightR = msg.LightRed;
                    me.tsInfo.lightR = msg.lightGreen;
                    me.tsInfo.lightW = msg.LightWhite;
                    me.tsInfo.lightw = msg.LightW;
                    me.tsInfo.currentTm = msg.CurrentTime;
                    me.tsInfo.currentSet = msg.SetIndex; 
                    if( me.changePosFlag==0){
                        me.tsInfo.homeScore = msg.ScoreLeft;
                        me.tsInfo.homeYello = msg.FlagYelloLeft;
                        me.tsInfo.homeRed = msg.FlagRedLeft;
                        me.tsInfo.homeWinFlag = msg.WinFlag==1?1:0;
                        me.tsInfo.awayScore = msg.ScoreRight;
                        me.tsInfo.awayYello = msg.FlagYelloRight;
                        me.tsInfo.awayRed = msg.FlagRedRight;
                        me.tsInfo.awayWinFlag = msg.WinFlag==2?1:0;
                    }
                    else{
                        me.tsInfo.awayScore = msg.ScoreLeft;
                        me.tsInfo.awayYello = msg.FlagYelloLeft;
                        me.tsInfo.awayRed = msg.FlagRedLeft;
                        me.tsInfo.awayWinFlag = msg.WinFlag==1?1:0;
                        me.tsInfo.homeScore = msg.ScoreRight;
                        me.tsInfo.homeYello = msg.FlagYelloRight;
                        me.tsInfo.homeRed = msg.FlagRedRight;
                        me.tsInfo.homeWinFlag = msg.WinFlag==2?1:0;  
                    }

                }
                catch(er){
                    console.log(er);
                }          
            },
            updateTsInfoTime( msg ) {
                var me = this;
                try{  
                    me.tsInfo.currentTm = msg.ct;
                }
                catch(er){
                    console.log(er);
                }          
            },
        },
        
    }
</script>

<style lang="less" scoped>
    @import url('./fe.less');
    .tsPage{
        background-color: #0b4383;
        color: #fff;
        display: flex;
        flex-direction: column;
        .header{
            padding: 20px;
            border-bottom: 5px solid #0077fe;
            .toolbar{
                display: flex;
                justify-content: space-between;
                align-items: center;
                .logo{
                    display: flex;
                    align-items: center;
                    .img{
                        height: 60px;
                        img{
                            height: 100%;
                            padding: 3px;
                            background-color: #fff;
                            border-radius: 2px;
                        }
                    }
                    .title{
                        padding-left: 10px;
                        .detail{
                            font-size: 1.2em;
                        }
                    }
                }
                .lights{
                    display: flex;
                    .lig{
                        margin: 0 10px;
                        width: 40px;
                        height: 40px;
                        border: 2px solid #fff;
                        border-radius: 50%;                        
                    }
                    .lig.R{
                        border: 2px solid #eb0c69;
                    }
                    .lig.R.active{ 
                        background-color:  #eb0c69;
                    }
                    .lig.G{
                        border: 2px solid rgb(22, 187, 17);
                    }
                    .lig.G.active{ 
                        background-color:  rgb(22, 187, 17);
                    }
                    .lig.W{
                        border: 2px solid #fafafa;
                    }
                    .lig.W.active{ 
                        background-color:  #fafafa;
                    }
                    .lig.w{
                         
                        border: 2px solid #fafafa; 
                    }
                    .lig.w.active{ 
                        background-color:  #fafafa;
                    }
                }
                .clockTime{
                    background-color: #eb0c69;
                    padding: 10px 0;
                    font-size: 2em;
                    font-weight: bold;
                    width: 120px;
                    text-align: center;
                    border-radius: 3px;
                }
                .acs{
                    ul.lstAcs{
                        display: flex;
                        li{
                            margin:0 10px;
                            background-color: #0077fe;
                            border-radius: 5px;
                            i{
                                height: 35px;
                                line-height: 40px;
                                width: 60px;
                                text-align: center;
                                font-size: 1.5em;
                            }
                            .txt{
                                height: 25px; 
                                width: 60px;
                                text-align: center;
                            }
                        }
                        li:active{
                            background-color: #2b87f1;
                        }
                    }
                }
            }
        }
        .body{
            flex: 1;
            padding: 20px;
            .pannel{
                display: flex;
                height: 100%;
                .player{
                    width:43%;
                    height: 100%;
                    display: flex;
                    flex-direction: column;
                    .athlete{
                        margin-bottom: 15px;
                        padding: 15px;
                        background-color: #0077fe;
                        display: flex;
                        font-size: 2em;
                        justify-content: space-around;
                    }
                    .result{
                        position: relative;
                        flex: 1;
                        background-color: #0077fe;
                        .score{
                            height: 400px;
                            line-height: 400px;
                            text-align: center;
                            text-align: center;
                            font-weight: bold;
                            font-size: 25em;
                        }
                        .flags{
                            position: absolute;
                            bottom: 0;
                            display: flex;
                            left: 50%;
                            transform: translate(-50%);
                            .flag{
                                margin: 15px;
                                width: 40px;
                                height: 60px;
                            }
                            .flag.yello{
                                border:2px solid rgb(250, 234, 7);
                            }
                            .flag.yello.active{
                                background-color: rgb(250, 234, 7);
                            }
                            .flag.red{
                                border:2px solid #eb0c69;
                            }
                            .flag.red.active{
                                background-color: #eb0c69;
                            }
                        }
                        .winFlag{
                            position: absolute;
                            left: 20px;
                            bottom: 20px; 
                            img{
                                width: 50px;
                                height: 50px;
                                border-radius: 10px;
                            }
                        }
                    }
                }
                .sets{
                    flex: 1;
                    position: relative;
                    
                    .timeClock{
                        background-color: #eb0c69;
                        margin: 0 auto;
                        height:70px;
                        line-height:70px;                        
                        font-size: 2em;
                        font-weight: bold;
                        width: 120px;
                        text-align: center;
                        border-radius: 3px;
                    }
                    ul.lstSets{
                        position: absolute;
                        left:50%;
                        top:50%;
                        transform: translate(-50%, -50%);
                        li{
                            .setItem{
                                height: 40px;
                                line-height: 40px;
                                margin: 10px;
                                border:1px solid #fff;
                                width: 90px;
                                text-align: center;
                                border-radius: 3px;
                                font-weight: 2.5em;
                                font-weight: bold;
                            }
                        }
                        li.active .setItem{
                            background-color: #eb0c69;
                        }
                    }
                }
            }
        }
    }
</style>